__author__ = 'wei'
'''
需要：
1.ANDROID_HOME 环境变量
2.projectDir 项目目录 必须以 / 结尾

Android 清空项目中无用的资源，反复调用lint指令,分析日志文件然后删除无用的文件

'''
import os
android_env_name = "ANDROID_HOME"
projectDir = "D:/workspace/FXIAO/fxiao-trunk/fxiaoke/"
logFile = "check.log"
del_tag_arr = ["res\\drawable", "res\\layout"]


# 处理文件路径 带空格的添加引号
def deal_file_path(file_path):
    old_arr = file_path.split("\\")
    new_str_arr = []
    for str1 in old_arr:
        if str1.__contains__(" "):
            new_str_arr.append("\"" + str1 + "\"")
        else:
            new_str_arr.append(str1)
    return "/".join(new_str_arr)


def _clear_unused_resource():
    if os.path.exists(logFile):
        os.remove(logFile)
    lint_path = os.getenv(android_env_name) + "/tools/"
    lint_path = deal_file_path(lint_path)
    os.system(lint_path + "/lint --check \"UnusedResources\" " + projectDir + " >> " + logFile)
    count = 0
    for line in open(logFile):
        if should_del(line):
            count += 1
            end = line.index(":")
            file = line[0:end]
            divider = ""
            del_file = projectDir + divider + file
            print("del file " + del_file)
            if os.path.exists(del_file):
                os.remove(del_file)
    return count


def should_del(line):
    if "UnusedResources" not in line:
        return False
    for tag in del_tag_arr:
        if tag in line:
            return True
    return False


if __name__ == '__main__':
    total_count = 0
    while True:
        clear_count = _clear_unused_resource()
        total_count += clear_count
        if clear_count == 0:
            break
    print("del " + str(total_count) + " file")

